import { Toast } from 'antd-mobile';
import axios from 'axios';
import React, { Component } from 'react';
import { AutoSizer, List } from 'react-virtualized';
import 'react-virtualized/styles.css';
import NavHeader from '../../components/NavHeader';
import { getLocation } from '../../utils';
import './index.scss';


/*
  1 将获取到的 cityObj 和 cityIndex  添加为组件的状态数据。
  2 修改 List 组件的 rowCount 为 cityIndex 的长度。
  3 将 rowRenderer 函数，添加到组件中，以便在函数中获取到状态数据 cityObj 和 cityIndex。
  4 修改 List 组件的 rowRenderer 为组件中的 rowRenderer 方法。
  5 修改 rowRenderer 方法中渲染的每行结构和样式。
  6 修改 List 组件的 rowHeight 为函数，动态计算每一行的高度（因为每一行高度都不相同）。

  <div key={key} style={style} className="city">
    <div className="title">S</div>
    <div className="name">上海</div>
  </div>
*/


function formatCityListData(list) {
  let cityObject = {};
  for (let i = 0; i < list.length; i++) {
    let item = list[i];
    let p = item.short.substr(0, 1);
    if (cityObject[p]) {
      cityObject[p].push(item);
    } else {
      cityObject[p] = [item];
    }
  }
  let cityIndex = Object.keys(cityObject).sort();

  return { cityObject, cityIndex };
}
const cityList = ['北京', '上海', '广州', '深圳'];
const titleHeight = 36;
const nameHeight = 50;
export default class CityList extends Component {

  state = {
    cityIndex: [],
    cityObject: {},
    curIndex: 0
  };

  listRef = React.createRef();

  componentDidMount() {
    this.getCityListDate();
  }

  // 获取数据
  async getCityListDate() {

    // 发送获取城市列表数据
    const res = await axios.get('http://localhost:8080/area/city?level=1');
    const { cityIndex, cityObject } = formatCityListData(res.data.body);

    // 发送获取热门城市数据
    const citres = await axios.get('http://localhost:8080/area/hot');

    // 获取当前城市位置数据
    const curCityInfo = await getLocation();

    cityIndex.unshift('hot');
    cityIndex.unshift('#');

    cityObject.hot = citres.data.body;
    cityObject['#'] = [curCityInfo];


    this.setState({
      cityIndex, cityObject
    }, () => {
      this.listRef.current.measureAllRows();
    });

  }

  // 计算数据的item的高度
  getRowHeight = ({ index }) => {
    let { cityIndex, cityObject } = this.state;
    let letter = cityIndex[index];
    let list = cityObject[letter];
    return titleHeight + nameHeight * list.length;
  };

  rowRenderer = ({
    key, // Unique key within array of rows
    index, // Index of row within collection
    isScrolling, // The List is currently being scrolled
    isVisible, // This row is visible within the List (eg it is not an overscanned row)
    style, // Style object to be applied to row (to position it)
  }) => {
    let { cityIndex, cityObject } = this.state;
    let letter = cityIndex[index];
    let list = cityObject[letter];
    let label = '';

    switch (letter) {
      case '#':
        label = '当前定位';
        break;
      case 'hot':
        label = '热门城市';
        break;
      default:
        label = letter.toUpperCase();
    }
    return (
      <div key={key} style={style} className="city">
        <div className="title">{label}</div>
        {list.map((item) => (
          <div className="name" onClick={this.changeCity.bind(this, item)} key={item.value}>{item.label}</div>
        ))}
      </div>
    );
  };

  renderCityIndex = () => {
    let { curIndex } = this.state;
    return this.state.cityIndex.map((v, i) => {
      let clsStr = `${curIndex === i ? 'index-active' : ' '}`;
      return (
        <li key={i} className='city-index-item' onClick={this.scrollTo.bind(this, i)}>
          <span className={clsStr}>{v == 'hot' ? '热' : v}</span>
        </li>
      );
    });
  };

  onRowsRendered = ({ startIndex }) => {
    const { curIndex } = this.state;
    if (curIndex !== startIndex) {
      this.setState({
        curIndex: startIndex
      });
    }
  };

  scrollTo(index) {
    this.listRef.current.scrollToRow(index);
  }

  changeCity(info) {
    if (cityList.indexOf(info.label) > -1) {
      localStorage.setItem('hkzf_city_56', JSON.stringify(info));
      this.props.history.go(-1);
    } else {
      Toast.info('该城市暂无房源信息！', 2, null, true);
    }
  };

  render() {
    return (
      <div className='cityList-warpper'>
        {/* <NavBar
          mode="light"
          icon={<i className='iconfont icon-back'></i>}
          onLeftClick={() => this.props.history.go(-1)}
        >城市列表</NavBar> */}
        <NavHeader>城市列表</NavHeader>

        <AutoSizer>
          {({ height, width }) => (
            <List
              width={width}
              height={height}
              rowCount={this.state.cityIndex.length}
              rowHeight={this.getRowHeight}
              rowRenderer={this.rowRenderer}
              onRowsRendered={this.onRowsRendered}
              ref={this.listRef}
              scrollToAlignment="start"
            />
          )}
        </AutoSizer>,

        <ul className='city-index'>
          {this.renderCityIndex()}
        </ul>
      </div>
    );
  }
}
